﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Windows.Forms;
using Microsoft.DirectX.DirectInput;

namespace gametest
{
    public class DxKeyboard
    {
        private Control target = null;
        private Device keyboard = null;

        public DxKeyboard(Control renderControl)
        {
            // 0. Save reference to target control 
            this.target = renderControl;

            // 1. Instantiate the  Device class to pass the type of device
            keyboard = new Device(SystemGuid.Keyboard);

            // 2. Set the cooperation level of the device
            keyboard.SetCooperativeLevel(this.target, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.NoWindowsKey);

            // 3. Set the format of the data that is returned by the device
            keyboard.SetDataFormat(DeviceDataFormat.Keyboard);

            // 4. Acquire the device
            keyboard.Acquire();
        }

        public KeyboardState GetKeyboardState()
        {
            KeyboardState state = null;
            do
            {
                try // try to get the current state 
                {
                    state = keyboard.GetCurrentKeyboardState();
                    break; // if fetching the state is successful -> exit loop 
                }
                catch (Exception)
                {
                    keyboard.Acquire(); // try to reacquire the keyboard
                }
            }
            while (true); // do this until it's successful
            return state; // return the retrieved keyboard state 
        }
    }
}
